package util

import (
	"bytes"
	"os"
)

// 定义文件类型签名（魔数）及其偏移量
var fileSignatures = map[string][]struct {
	Offset int
	Magic  []byte
}{
	"image/jpeg": {
		{Offset: 0, Magic: []byte{0xFF, 0xD8}}, // JPEG 文件头
	},
	"image/png": {
		{Offset: 0, Magic: []byte{0x89, 0x50, 0x4E, 0x47}}, // PNG 文件头
	},
	"application/pdf": {
		{Offset: 0, Magic: []byte{0x25, 0x50, 0x44, 0x46}}, // %PDF-
	},
	"video/mp4": {
		{Offset: 4, Magic: []byte{0x66, 0x74, 0x79, 0x70}}, // MP4 的 ftyp 标记
	},
	// 添加更多类型...
}

func GetTypeByMagic(path string) string {
	file, err := os.Open(path)
	if err != nil {
		return "error"
	}
	defer file.Close()

	// 读取足够长的字节（覆盖最大偏移量需求）
	buffer := make([]byte, 1024)
	n, err := file.Read(buffer)
	if err != nil || n < 1024 {
		return "error"
	}

	// 遍历所有已知类型进行匹配
	for mimeType, signatures := range fileSignatures {
		match := true
		for _, sig := range signatures {
			offset := sig.Offset
			end := offset + len(sig.Magic)
			if end > len(buffer) {
				match = false
				break
			}
			if !bytes.Equal(buffer[offset:end], sig.Magic) {
				match = false
				break
			}
		}
		if match {
			return mimeType
		}
	}
	return "unknown"
}
